﻿/// <reference path="D:\DEV\VS2013\fileman_net\FileManNet\FileMan\FileMan\fileUploadDialog.html" />
/// <reference path="D:\DEV\VS2013\fileman_net\FileManNet\FileMan\FileMan\fileUploadDialog.html" />
(function () {
    // define the angular application
    var app = angular.module('fileMan', ['mgcrea.ngStrap.modal', 'mgcrea.ngStrap.aside', 'angularFileUpload']);
    // define the application variables
    var appFiles = [];
    // Angular controllers:
    app.controller('FilesControler', ['$http','$aside','$scope','$modal',function ($http,$aside,$scope,$modal) {
        this.files = [];
        appThis = this;
        $http.post('filemanServices.aspx/getFiles', {}).success(function (data) {
            appThis.files = data.d;
            appThis.uiLines = undefined;
        });
        this.uiLines = undefined;
        this.currentFolder = 'root';
        this.folderTrail = ['root']
        this.getFilename = function (file) {
            var name = '';
            if (file.type !== 'folder')
            {
                name = file.name + '.' + file.type;
            }
            else
            {
                name = file.name;
            }
            return name
        };
        this.clickFile = function (file) {
            if ((file.type === "folder")) {
                if (file.name !== ".."){
                    this.currentFolder = file.name;
                    this.folderTrail.push(file.name);
                }
                else {
                    this.folderTrail.pop();
                    this.currentFolder = this.folderTrail[this.folderTrail.length - 1];
                }
                var back = {
                    type: 'folder',
                    name: '..',
                    content: this.files,
                    path: '..',
                    thumbnail: '\\Icons\\folder_return.png',
                    level: (file.level - 1)
                };
                this.files = file.content;
                if ((file.level > 0) && (!containsObject(back, this.files)) && (file.name !== "..")) {
                    this.files.unshift(back);
                }
            }
            else {
                selectedFile = file;
                myAside = $aside({scope: $scope,template: 'fileDialog.html',title: file.name,contentTemplate: 'fileDialogInner.html'});
                myAside.$promise.then(function(){
                    myAside.show();
                })
            }
            this.uiLines = undefined;
        };
        this.getUiLines = function (tiles) {
            var lines = [];
            if (this.uiLines === undefined) {
                for (var i = 0; (i * tiles) < this.files.length; i++) {
                    var line = [];
                    for (var y = 0; y < tiles; y++) {
                        if (((i * tiles) + y) < this.files.length) {
                            line.push(this.files[(i * tiles) + y]);
                        }
                    }
                    lines.push(line);
                }
                this.uiLines=lines
            }
            return this.uiLines;
        };
        this.getCurrentFolder = function () { return buildFolderTrail(this.folderTrail); };
        this.refresh = function () {
            $http.post('filemanServices.aspx/getFiles', {}).success(function (data) {
                appThis.files = data.d;
                //var parent = appThis.files;
                var trail = appThis.folderTrail.slice();
                appThis.folderTrail = ['root'];
                for (var i = 1; i<(trail.length) ; i++)
                {
                    var tempFile = appThis.findFile(trail[i]);
                    if (tempFile !== undefined)
                    {
                        appThis.clickFile(tempFile);
                    }
                }                
                appThis.uiLines = undefined;
            });
        };
        this.findFile = function (filename) {
            var foundFile = {};
            for (i=0; i<appThis.files.length;i++)
            {
                if (appThis.files[i].name === filename)
                {
                    foundFile = appThis.files[i];
                }
            }
            return foundFile;
        };
        this.startNewFolder = function () {
            newFolderModal = $modal({ scope: $scope, template: 'newFolder.html', show: false, title: "Add Folder" });
            // Show when some event occurs (use $promise property to ensure the template has been loaded)
            newFolderModal.$promise.then(function () { newFolderModal.show(); });
        };
        this.startUpload = function () {
            uploadModal = $modal({ scope: $scope, template: 'fileUploadDialog.html', show: false, title: "Upload File" });
            // Show when some event occurs (use $promise property to ensure the template has been loaded)
            uploadModal.$promise.then(function () { uploadModal.show(); });

        };
    }]);
    //
    app.controller('UploadController', ['$scope', 'FileUploader', function ($scope, $FileUploader) {
        var uploader = $scope.uploader = new $FileUploader({
            url: 'filemanServices.aspx/upload'
        });

        // FILTERS

        uploader.filters.push({
            name: 'customFilter',
            fn: function (item /*{File|FileLikeObject}*/, options) {
                return this.queue.length < 10;
            }
        });

        // CALLBACKS

        uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
            console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfterAddingFile = function (fileItem) {
            console.info('onAfterAddingFile', fileItem);
        };
        uploader.onAfterAddingAll = function (addedFileItems) {
            console.info('onAfterAddingAll', addedFileItems);
        };
        uploader.onBeforeUploadItem = function (item) {
            console.info('onBeforeUploadItem', item);
        };
        uploader.onProgressItem = function (fileItem, progress) {
            console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function (progress) {
            console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function (fileItem, response, status, headers) {
            console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function (fileItem, response, status, headers) {
            console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function (fileItem, response, status, headers) {
            console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function (fileItem, response, status, headers) {
            console.info('onCompleteItem', fileItem, response, status, headers);
        };
        uploader.onCompleteAll = function () {
            console.info('onCompleteAll');
        };

        console.info('uploader', uploader);
    }]);
    //
    app.controller('FileDialogController', ['$http','$scope', function ($http,$scope) {
        this.file = selectedFile;
        var dialogThis = this;
        this.delete = false;
        this.rename = false;
        this.newName = "";
        this.copy = false;
        this.move = false;
        this.newLocation = "";
        // Delete
        this.canDelete = function () {
            var ok = false;
            if (!this.rename && !this.copy && !this.move ) {
                ok = true;
            }
            return ok;
        };
        this.setDelete = function () { if (this.canDelete()) { this.delete = true; } };
        this.cancelDelete = function () { this.delete = false; };
        this.doDelete = function () {
            $http.post('filemanServices.aspx/deleteFile', { filename: this.file.name, path: this.file.path }).success(function (data) {
                appThis.refresh();
                myAside.hide();
            });
        };
        // Rename
        this.canRename = function () {
        var ok = false;
        if ( !this.copy && !this.move && !this.delete) {
            ok = true;
        }
        return ok;
        };
        this.setRename = function () {
            if (this.canRename()) { this.rename = true; }
        };
        this.cancelRename = function () { this.rename = false; };
        this.doRename = function () {
            $http.post('filemanServices.aspx/renameFile', { filename: this.file.name, path: this.file.path, newName: this.newName }).success(function (data) {
                appThis.refresh();
                myAside.hide();
            });
        };
        // Copy
        this.doCopy = function () {
            $http.post('filemanServices.aspx/copyFile', { filename: this.file.name, path: this.file.path }).success(function (data) {
                appThis.refresh();
                myAside.hide();
            });
        };
        // Move
        this.folderStruct = [];
        this.canMove = function () {
            var ok = false;
            if (!this.rename && !this.copy && !this.delete) {
                ok = true;
            }
            return ok
        };
        this.setMove = function () {
            if (this.canMove()) {
                this.move = true;
                // Build folder structure
                $http.post('filemanServices.aspx/getFiles', {}).success(function (data) {
                    dialogThis.addFoldersToStruct('root\\', data.d);
                });
            }
        };
        this.addFoldersToStruct = function (path, folder) {
            dialogThis.folderStruct.push(path)
            for ( var i = 0; i < folder.length; i++)
            {
                if ( folder[i].type === 'folder')
                {
                    dialogThis.addFoldersToStruct(path + '\\' + folder[i].name, folder[i].content);
                }
            }
        };
        this.cancelMove = function () { this.move = false; }
        this.doMove = function () {
            this.newLocation = this.newLocation.substr(this.newLocation.indexOf('\\') + 1);
            $http.post('filemanServices.aspx/moveFile', { filename: this.file.name, path: this.file.path, newPath: this.newLocation }).success(function (data) {
                appThis.refresh();
                myAside.hide();
            });
        };
    }]);
    //
    app.controller('AddFolderController', ['$http', '$scope', function ($http, $scope) {
        this.folderName = '';
        this.addFolder = function () {
            $http.post('filemanServices.aspx/addFolder', { folder: this.folderName, path: buildFolderTrail(appThis.folderTrail) }).success(function (data) {
                appThis.refresh();
                newFolderModal.hide();
            });
        };
    }]);
    // helper functions
    var containsObject = function (obj, lst) {
        var i;
        if (lst !== undefined) {
            for (i = 0; i < lst.length; i++) {
                if (angular.equals(lst[i], obj)) { return true; }
            }
        }
        return false;
    };
    var buildFolderTrail = function (folderTrail) {
        var name = '';
        for (var i = 0; i < folderTrail.length; i++) {
            name = name + folderTrail[i] + '\\';
        }
        return name;
    };
    // helper variables
    var selectedFile;
    var myAside;
    var uploadModal;
    var newFolderModal;
})()